package com.hxzy.bbs.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;

import com.hxzy.jsp.connection.JNDIBBSConection;
import com.hxzy.jsp.entity.User;
import com.hxzy.jsp.session.ErrorCode;
import com.hxzy.jsp.utils.Connections;
import com.hxzy.jsp.utils.Hashs;
import com.mysql.jdbc.StringUtils;

public class LoginServlet extends AppServlet {
	private static final long serialVersionUID = 1L;

	public LoginServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String passwd = request.getParameter("passwd");
		String remeberMe = request.getParameter("remeber_me");

		if (StringUtils.isEmptyOrWhitespaceOnly(username)) {
			response.sendRedirect("./error?error=" + ErrorCode.FIELD_REQUIRE);
			return;
		}
		if (StringUtils.isEmptyOrWhitespaceOnly(passwd)) {
			response.sendRedirect("./error?error=" + ErrorCode.FIELD_REQUIRE);
			return;
		}

		Calendar c = Calendar.getInstance();

		User user = null;
		Connection conn = new JNDIBBSConection().get();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.prepareStatement("select * from `stu_bbs`.`user` where username = ? limit 1");
			stmt.setString(1, username);

			rs = stmt.executeQuery();
			while (rs.next()) {
				String _passwd = rs.getString("passwd");
				String _salt = rs.getString("salt");
				if (!_passwd.equals(DigestUtils.sha1Hex((_salt + passwd).getBytes()))) {
					break;
				}
				user = new User(rs.getLong("id"), rs.getString("username"), rs.getString("nickname"), null,
						c.getTimeInMillis() / 1000, User.USER);
				break;
			}
			if (user == null) {
				response.sendRedirect("./error?error=" + ErrorCode.USER_LOGIN_FAILED); // 用户名或者密码错误
				return;
			}
			request.getSession().setAttribute("user", user);

			// 记录登陆 ip，记录登陆时间
			long now = (int) (c.getTimeInMillis() / 1000);
			int rowIndex = 1;
			stmt.close();
			
			stmt = conn.prepareStatement(
					"update `stu_bbs`.`user` set ip_login = ?, gmt_login = ?, gmt_modified = ?, hash = ?, gmt_hash_expires = ? "
							+ " where id = ?");
			stmt.setString(rowIndex++, request.getRemoteAddr());
			stmt.setLong(rowIndex++, now);
			stmt.setLong(rowIndex++, now);

			// 更新登陆 hash，保存在 cookie 里
			if ("1".equals(remeberMe)) {
				int timeout = 2*60;
				String hash = DigestUtils.sha1Hex(Hashs.createSalt() + request.getRemoteAddr());

				Cookie cookie = new Cookie("h", hash);
				cookie.setMaxAge(timeout); // 盐值存储一天
				response.addCookie(cookie);

				stmt.setString(rowIndex++, hash);
				stmt.setLong(rowIndex++, (now + timeout));
			} else {
				Cookie cookie = new Cookie("h", null);
				cookie.setMaxAge(0);
				response.addCookie(cookie);

				stmt.setString(rowIndex++, "");
				stmt.setLong(rowIndex++, 0);
			}
			stmt.setLong(rowIndex++, user.getId());
			stmt.execute();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		response.sendRedirect("./index");
	}

}
